using HealthChecks.UI.Client;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;

namespace BuildingBlocks.Infrastructure.HealthChecks;

public static class HealthCheckModule
{
    public static IServiceCollection AddCustomHealthChecks(this IServiceCollection services, IConfiguration configuration)
    {
        var connectionString = configuration.GetConnectionString("Default")
            ?? throw new InvalidOperationException("Connection is not configured.");

        services.AddHealthChecks()
            .AddNpgSql(connectionString, name: "PostgreSQL")
            .AddCheck("self", () => HealthCheckResult.Healthy());

        /*  services.AddHealthChecksUI(setup =>
         {
             setup.AddHealthCheckEndpoint("Catalog API", "/health");
         }); */
        // .AddInMemoryStorage(); // 也可以使用 SQL 存储

        return services;
    }

    public static IApplicationBuilder UseCustomHealthChecks(this IApplicationBuilder app)
    {
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHealthChecks("/health", new HealthCheckOptions
            {
                Predicate = _ => true,
                ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
            });

            /*  endpoints.MapHealthChecksUI(options =>
             {
                 options.UIPath = "/health-ui";
             }); */
        });

        return app;
    }
}
